const { exec } = require('child_process');
const util = require('util');

const execAsync = util.promisify(exec);

class DeviceDebugger {
    constructor() {
        this.adbPath = 'adb';
        this.scrcpyPath = 'scrcpy';
    }

    async runCommand(command, description) {
        try {
            console.log(`🔍 ${description}...`);
            const { stdout, stderr } = await execAsync(command);
            if (stdout) {
                console.log(`✅ ${description}成功:`);
                console.log(stdout);
            }
            if (stderr) {
                console.log(`⚠️ ${description}警告:`);
                console.log(stderr);
            }
            return { success: true, output: stdout, error: stderr };
        } catch (error) {
            console.log(`❌ ${description}失败:`);
            console.log(error.message);
            return { success: false, error: error.message };
        }
    }

    async checkAdbInstallation() {
        console.log('=======================================');
        console.log('🔧 ADB 安装检查');
        console.log('=======================================');
        
        const result = await this.runCommand('adb version', '检查ADB版本');
        if (result.success) {
            console.log('✅ ADB已正确安装');
        } else {
            console.log('❌ ADB未安装或不在PATH中');
            console.log('请下载Android SDK Platform Tools并添加到系统PATH');
            console.log('下载地址: https://developer.android.com/studio/releases/platform-tools');
        }
        console.log('');
    }

    async checkScrcpyInstallation() {
        console.log('=======================================');
        console.log('🔧 scrcpy 安装检查');
        console.log('=======================================');
        
        const result = await this.runCommand('scrcpy --version', '检查scrcpy版本');
        if (result.success) {
            console.log('✅ scrcpy已正确安装');
        } else {
            console.log('❌ scrcpy未安装或不在PATH中');
            console.log('请下载scrcpy并添加到系统PATH');
            console.log('下载地址: https://github.com/Genymobile/scrcpy/releases');
        }
        console.log('');
    }

    async checkAdbServer() {
        console.log('=======================================');
        console.log('🔧 ADB 服务状态检查');
        console.log('=======================================');
        
        // 检查ADB服务状态
        await this.runCommand('adb start-server', '启动ADB服务');
        
        // 等待服务启动
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        // 检查服务状态
        await this.runCommand('adb devices', '检查已连接设备');
        console.log('');
    }

    async checkUsbDrivers() {
        console.log('=======================================');
        console.log('🔧 USB 驱动检查');
        console.log('=======================================');
        
        console.log('请检查以下项目:');
        console.log('1. 设备管理器中是否有未知设备或感叹号');
        console.log('2. 是否安装了设备厂商的USB驱动');
        console.log('3. 尝试不同的USB线缆');
        console.log('4. 尝试不同的USB端口');
        console.log('');
    }

    async checkDeviceSettings() {
        console.log('=======================================');
        console.log('🔧 设备设置检查');
        console.log('=======================================');
        
        console.log('请在安卓设备上检查以下设置:');
        console.log('');
        console.log('📱 开发者选项:');
        console.log('   1. 设置 → 关于手机 → 版本号 (点击7次)');
        console.log('   2. 设置 → 开发者选项 → 开启');
        console.log('');
        console.log('🔌 USB调试:');
        console.log('   1. 设置 → 开发者选项 → USB调试 (开启)');
        console.log('   2. 设置 → 开发者选项 → USB调试(安全设置) (开启)');
        console.log('');
        console.log('🔐 授权调试:');
        console.log('   1. 连接USB后，设备会弹出"允许USB调试"对话框');
        console.log('   2. 勾选"始终允许来自这台计算机"');
        console.log('   3. 点击"确定"');
        console.log('');
    }

    async runNetworkTest() {
        console.log('=======================================');
        console.log('🔧 网络连接测试');
        console.log('=======================================');
        
        try {
            const { stdout } = await execAsync('netstat -an | findstr :5037');
            if (stdout.includes('5037')) {
                console.log('✅ ADB服务端口5037正在监听');
            } else {
                console.log('❌ ADB服务端口5037未监听');
            }
        } catch (error) {
            console.log('❌ 无法检查ADB服务端口');
        }
        console.log('');
    }

    async runFullDiagnostic() {
        console.log('🚀 开始设备连接诊断...\n');
        
        await this.checkAdbInstallation();
        await this.checkScrcpyInstallation();
        await this.checkAdbServer();
        await this.runNetworkTest();
        await this.checkUsbDrivers();
        await this.checkDeviceSettings();
        
        console.log('=======================================');
        console.log('📋 诊断完成！');
        console.log('=======================================');
        console.log('');
        console.log('如果仍然无法检测到设备，请尝试:');
        console.log('1. 重启ADB服务: adb kill-server && adb start-server');
        console.log('2. 重启安卓设备');
        console.log('3. 重启电脑');
        console.log('4. 检查USB线缆是否支持数据传输');
        console.log('5. 尝试在其他电脑上测试');
        console.log('');
        console.log('常见解决方案:');
        console.log('- 更换USB线缆');
        console.log('- 使用USB 2.0端口');
        console.log('- 安装设备厂商的专用驱动');
        console.log('- 在设备上撤销USB调试授权后重新授权');
    }

    async interactiveTroubleshooting() {
        console.log('=======================================');
        console.log('🔧 交互式故障排除');
        console.log('=======================================');
        
        const readline = require('readline');
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });

        const question = (query) => new Promise((resolve) => rl.question(query, resolve));

        try {
            console.log('请回答以下问题来帮助诊断问题:\n');

            const hasDevice = await question('1. 您的安卓设备是否已通过USB连接到电脑？(y/n): ');
            if (hasDevice.toLowerCase() !== 'y') {
                console.log('❌ 请先连接设备到电脑');
                rl.close();
                return;
            }

            const hasDeveloperOptions = await question('2. 是否已在设备上开启开发者选项？(y/n): ');
            if (hasDeveloperOptions.toLowerCase() !== 'y') {
                console.log('❌ 请在设备上开启开发者选项');
                console.log('设置 → 关于手机 → 版本号 (点击7次)');
                rl.close();
                return;
            }

            const hasUsbDebug = await question('3. 是否已开启USB调试？(y/n): ');
            if (hasUsbDebug.toLowerCase() !== 'y') {
                console.log('❌ 请在开发者选项中开启USB调试');
                rl.close();
                return;
            }

            const hasAuthorized = await question('4. 连接USB后是否看到"允许USB调试"对话框？(y/n): ');
            if (hasAuthorized.toLowerCase() !== 'y') {
                console.log('❌ 请检查USB连接和驱动');
                console.log('尝试更换USB线缆或端口');
                rl.close();
                return;
            }

            console.log('\n✅ 所有设置看起来都正确！');
            console.log('让我们重新测试连接...\n');
            
            await this.checkAdbServer();
            
        } catch (error) {
            console.log('交互式故障排除出错:', error.message);
        } finally {
            rl.close();
        }
    }
}

// 主函数
async function main() {
    const deviceDebugger = new DeviceDebugger();
    
    if (process.argv.includes('--interactive')) {
        await deviceDebugger.interactiveTroubleshooting();
    } else {
        await deviceDebugger.runFullDiagnostic();
    }
}

// 运行诊断
if (require.main === module) {
    main().catch(console.error);
}

module.exports = DeviceDebugger; 